package org.cloudie.docs.editor.client.content.dialogs;

import org.cloudie.docs.editor.client.widgets.Dialog;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;

/**
 * A dialog window displaying a selection of images.
 */
public class SelectImageDialog extends Dialog {

  protected static SelectImageDialog instance;
  
  public static SelectImageDialog get(String urlPattern, String[] ids) {
    if (instance == null) {
      instance = new SelectImageDialog();
    }
    if (ids != null) {
      instance.setImages(urlPattern, ids);
    }
    return instance;
  }
  
  protected ScrollPanel scroller;
  protected FlowPanel content;
  protected String selectedImage;
  protected SelectionHandler<String> handler;
	
  /**
   * Constructs an image selection dialog window.
   */
  protected SelectImageDialog() {
    super("Select Image", true);
    addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
        hide();
		if (handler != null) {
	      ImageSelectionEvent e = new ImageSelectionEvent(null);
		  handler.onSelection(e);
		}
      }
    });
    content = new FlowPanel();
    content.setSize("100%", "100%");
    scroller = new ScrollPanel();
    scroller.add(content);
    scroller.setSize("400px", "230px");
    setContentWidget(scroller);
  }
  
  public String getSelectedImage() {
	return selectedImage;
  }
  
  public void setImages(String urlPattern, String[] ids) {
	content.clear();
	for (final String id : ids) {
	  Image img = new Image();
	  img.setStylePrimaryName("cloudie-ImageSelection-Item");
	  img.setUrl(urlPattern.replace("%1", id));
	  img.addClickHandler(new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
		  hide();
		  if (handler != null) {
			selectedImage = id;
			ImageSelectionEvent e = new ImageSelectionEvent(selectedImage);
			handler.onSelection(e);
		  }
		}
	  });
	  content.add(img);
	}
  }
  
  public void center(SelectionHandler<String> handler) {
	super.center();
	this.handler = handler;
  }
  
  public class ImageSelectionEvent extends SelectionEvent<String> {

	public ImageSelectionEvent(String selectedItem) {
	  super(selectedItem);
	}
	
  }
}
